package com.frinder.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Created by kiktech on 2017/8/4.
 */
@Slf4j
public class NettyServerInitializer extends ChannelInitializer<Channel> {

    // read time out
    private static final int READ_IDEL_TIME_OUT = 4;
    // write time out
    private static final int WRITE_IDEL_TIME_OUT = 5;
    // all time out
    private static final int ALL_IDEL_TIME_OUT = 7;

    private ChannelGroup channels;

    public NettyServerInitializer(ChannelGroup channels) {
        this.channels = channels;
    }

    @Override
    protected void initChannel(Channel channel) throws Exception {
        log.debug("initChannel Begin!");
        ChannelPipeline pipeline = channel.pipeline();
        // logger
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));

        // heart beat
        pipeline.addLast(new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.SECONDS));
        pipeline.addLast(new HeartbeatHandler());

        // encode & decode
        pipeline.addLast(MarshallingCodeCFactory.decoder());
        pipeline.addLast(MarshallingCodeCFactory.encoder());

        // client handler
        pipeline.addLast(new ClientManagerHandler(channels));

        // message handler
        pipeline.addLast(new MessageHanlder());

        log.debug("initChannel Complete!");
    }

}
